package com.tydic.springboot.excel.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.tydic.springboot.util.HttpServletUtil;
import com.tydic.springboot.util.easyExcel2.CascadeVO;
import com.tydic.springboot.util.easyExcel2.CascadeWriteHandler;
import com.tydic.springboot.util.easyExcel2.DropDownVO;
import com.tydic.springboot.util.easyExcel2.DropDownWriteHandler;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @SneakyThrows
    @GetMapping("/downloadCascade")
    public void downloadCascade(HttpServletRequest request, HttpServletResponse response) {
        HttpServletUtil.setResponse(request, response, "导出模板-级联下拉框");

        List<CascadeVO> dataList = new ArrayList<>();

        // 准备要写出的数据（这里可以从数据库中查询出来后再进行）
        // 查询所有的省名称
        List<String> provNameList = new ArrayList<String>();
        provNameList.add("浙江省");
        provNameList.add("广东省");

        // 整理数据，放入一个Map中，mapkey存放父地点，value 存放该地点下的子区域
        Map<String, List<String>> siteMap = new HashMap<String, List<String>>();

        siteMap.put("浙江省", CollUtil.newArrayList("杭州市", "金华市", "宁波市"));
        siteMap.put("广东省", CollUtil.newArrayList("广州市", "深圳市", "韶光市"));

        // 写出数据
        EasyExcel.write(response.getOutputStream(), CascadeVO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("sheet1")
                .registerWriteHandler(new CascadeWriteHandler(provNameList, siteMap))
                .doWrite(dataList);
    }

    @SneakyThrows
    @GetMapping("downloadDropDown")
    public void downloadDropDown(HttpServletRequest request, HttpServletResponse response) {
        HttpServletUtil.setResponse(request, response, "导出模板-普通下拉框");

        List<CascadeVO> dataList = new ArrayList<>();

        // 准备要写出的数据（这里可以从数据库中查询出来后再进行）
        List<String> dropDown = CollUtil.newArrayList("男", "女");

        // 写出数据
        EasyExcel.write(response.getOutputStream(), DropDownVO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("sheet1")
                .registerWriteHandler(new DropDownWriteHandler(dropDown))
                .doWrite(dataList);
    }
}

